import { useRouter } from 'vue-router'
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import Utils from '@/utils/commonUtils'
import routerMap, { permissionMenu } from '@/router/router'
export const useMenuStore = defineStore('menu', () => {
  const $router = useRouter()
  // 获取路由数组
  const currentRouter: any = ref<any>([])
  // 判断是否有菜单权限
  const hasMenu = (name: string) => currentRouter.value.some((item: any) => item.name === name && !item.isShow)
  // 递归改变菜单权限
  const mapTree = (org: any) => {
    return org.map((item: any) => {
      const haveChildren = Array.isArray(item.children) && item.children.length > 0
      return {
        ...item,
        meta: {
          ...item.meta,
          isShow: permissionMenu.some((el) => el === item.name) ? true : item.meta.isShow
        },
        children: haveChildren ? mapTree(item.children) : []
      }
    })
  }
  /**
   * 页面跳转
   * @param name 路由name
   * @param param1 {Object} 需要传递的参数
   */
  const jumpPage = (
    name: string,
    {
      params,
      query
    }: { params?: Record<string, any>; query?: Record<string, any> }
  ) => {
    if (hasMenu(name)) {
      $router.push({ name, params, query })
    } else {
      Utils.openNotification('error', '暂无权限，请联系管理员')
      console.warn(`没有找到对应的页面: ${name}`)
    }
  }
  // 路由前进或后退
  const go = (step: number) => $router.go(step)
  // 监听登录状态，改变路由
  watch(
    () => Utils.LocalStore.get('isLogin'),
    () => {
      // const arr = routerMap.shift()
      // console.log(mapTree(arr));
      const isLogin = Utils.LocalStore.get('isLogin')
      routerMap.shift()
      if (isLogin === 'true') {
        currentRouter.value = mapTree(routerMap)
      } else {
        currentRouter.value = routerMap
      }
    },
    { immediate: true }
  )
  return {
    currentRouter,
    jumpPage,
    go
  }
})
